// 获取标签
const go_login = document.querySelector('.go_login')
const logout = document.querySelector('.logout')
const loginDiv = document.querySelector('.login')
const nickDiv = document.querySelector('.nick')
const nickP = document.querySelector('.nickP')
const go_cart = document.querySelector('.go_cart')
const searchInp = document.querySelector('.search_inp input')
const ul = document.querySelector('.search_inp ul')
const back = document.querySelector('.back')
const h_box = document.querySelector('.h_box')

const login = window.localStorage.getItem('login')
const nick = window.localStorage.getItem('nick')

nickHtml()
function nickHtml() {
    if (!login) {
        loginDiv.classList.add('active')
        return
    }
    nickDiv.classList.add('active')

    // 登录过将用户名写入
    nickP.innerText = 'hello ' + nick
}

// 给帮助中心添加鼠标移入事件,移入时给盒子添加类名让其显示
$('.help').mouseover(function () {
    $('.help_box').stop().slideDown(300, 'linear')//.addClass('active')
})
$('.help').mouseout(function () {
    $('.help_box').stop().slideUp(300, 'linear')//.addClass('active')
})

// 在线咨询
$('.consult').mouseover(function () {
    $(this).addClass('active')
})
$('.consult').mouseout(function () {
    $(this).removeClass('active')
})
// 登录注册下滑盒子
$('.login').mouseover(function () {
    $('.login_box').stop().slideDown(500, 'linear')
})
$('.login').mouseleave(function () {
    $('.login_box').stop().slideUp(500, 'linear')
})
// 注销登录盒子的显示
$('.nick').mouseover(function () {
    $('.nick_box').stop().slideDown(500, 'linear')
})
$('.nick').mouseleave(function () {
    $('.nick_box').stop().slideUp(500, 'linear')
})

// 登录事件
go_login.addEventListener('click', () => {
    window.location.href = './login.html'
})

// 注销绑定事件
logout.onclick = () => {
    window.localStorage.removeItem('id')
    window.localStorage.removeItem('login')
    window.localStorage.removeItem('nick')
    nickDiv.classList.remove('active')
    loginDiv.classList.add('active')
}



// 跳转购物车
go_cart.onclick = function () {
    // 获取login 没有的话代表没有登陆过 需要先登录
    if (!login) {
        alert('您还没有登录哦,请先登录吧^_^')
        window.location.href = './login.html'
        return
    }
    window.location.href = './cart.html'
}

// 二级菜单
// 获取li的index,上边ul的li索引-1对应的是下边要显示的li
$('.nav_box>li').mouseover(function () {
    const index = $(this).index()
    let i = index - 1
    if (i >= 0) {
        $('.header_box>li').eq(i).finish().slideDown(300, 'linear').siblings().finish().slideUp(0)
    }
})
$('.header_box').mouseleave(function () {
    $('.header_box>li').finish().slideUp(0)
})


$('.search').mouseover(function () {
    $('.search_inpbox').stop().slideDown(500, 'linear')//.addClass('active')
})
$('.search').mouseout(function () {
    $('.search_inpbox').stop().slideUp(500, 'linear')//.addClass('active')
})
// 二级菜单跳转列表页
const nav_box = document.querySelectorAll('.nav_box>li')
nav_box.forEach(item => {
    item.onclick = function () {
        window.location.href = './list.html'
    }
})
// 搜索引擎
searchInp.oninput = function () {
    const text = this.value.trim()
    const script = document.createElement('script')
    script.src = `https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=34305,34099,33970,34273,34278,34004,34281,34107,34111,26350,22159&wd=${text}&req=2&csor=2&cb=fn&_=1627023610785`
    document.body.appendChild(script)

    script.remove()
}
function fn(res) {
    if (!res.g) {
        ul.classList.remove('active')
        return
    }
    let str = ''
    res.g.forEach(item => {
        str += `<li>${item.q}</li>`
    })

    ul.innerHTML = str

    ul.classList.add('active')
}

// 给返回顶部的图片添加事件
window.addEventListener('scroll', function () {
    const scrollTop = document.documentElement.scrollTop
    if (scrollTop >= 300) {
        back.classList.add('active')
    } else {
        back.classList.remove('active')
    }
})
back.addEventListener('click', () => {
    window.scrollTo({
        top: 0,
        behavior: "smooth"
    })
})


// 轮播图
var mySwiper = new Swiper('.swiper-container', {
    loop: true, // 循环模式选项
    autoplay: {
        delay: 2000,
        disableOnInteraction: false
    },
    // 如果需要分页器
    pagination: {
        el: '.swiper-pagination',
        clickable: true,
    },
    // 如果需要前进后退按钮
    navigation: {
        nextEl: '.swiper-button-next',
        prevEl: '.swiper-button-prev',
    }
})



// 产品页,发送请求
const xhr = new XMLHttpRequest
xhr.open('POST', '/hln')
xhr.onload = () => {
    bindHtml(xhr, 0)
    clickHtml(xhr)
}
xhr.setRequestHeader('content-type', 'application/json')
xhr.send('{"searchProductCodeList":["HROF00000017","HROF00000020","HROF00000009","HROF00000014","HROF00000010","HRNF00000107"],"searchOffSaleProduct":false,"isRestrictPurchase":false}');

function bindHtml(xhr, index) {
    const res = JSON.parse(xhr.responseText)

    const list = res.serializableData.aggResult.productList
    let n = index + 1
    let num = 3
    const arr = list.slice((n - 1) * num, n * num)
    let str = ''
    arr.forEach(item => {
        str += `
        <ol class="hot_b active">
            <li class="product">
                <div class="product_box">
                <div class="p_img">
                    <img data-id="${item.id}" src="${item.productImageDefault}" alt="">
                    <p class="p_t1">${item.channelProductName}</p>
                    <p class="p_t2">${item.productNameEn}</p>
                    <p class="p_t3"><span>￥</span>${item.channelPriceList[0]}</p>
                    <select>
                    <option value="${item.variantCustValueList[0]}">${item.variantCustValueList[0]}</option>
                    <option value="${item.variantCustValueList[1]}">${item.variantCustValueList[1]}</option>
                    <option value="${item.variantCustValueList[2]}">${item.variantCustValueList[2]}</option>
                    </select>
                    <button data-id="${item.id}" class="buy_btn">立即购买</button>
                </div>
                </div>
            </li>
        </ol>
        `
    })
    h_box.innerHTML = str
    str = ''

    // 选项卡
    // 获取标签
    const hot_tbtn = document.querySelectorAll('.hot_t>li')
    const hot_bbtn = document.querySelectorAll('.hot_b')
    hot_tbtn.forEach(function (item, index) {

        item.onclick = function () {
            bindHtml(xhr, index)

            console.log(hot_bbtn)
            for (var i = 0; i < hot_tbtn.length; i++) {
                // console.log(hot_bbtn)
                hot_tbtn[i].classList.remove('active')
                hot_bbtn[i].classList.remove('active')
            }

            hot_tbtn[index].classList.add('active')
            hot_bbtn[index].classList.add('active')

        }
    })
}

function clickHtml(xhr){
    const res = JSON.parse(xhr.responseText)
    const list = res.serializableData.aggResult.productList
     // 给图片绑定跳转详情页事件
     const h_box = document.querySelector('.h_box')
     h_box.addEventListener('click',e=>{
         e = e || window.event
         const target = e.target || e.srcElement
         if(target.nodeName==='IMG'){
             console.log(111)
             const goodsId = target.dataset.id
             window.localStorage.setItem('product_id',goodsId)
             window.location.href='./detail.html'
         }
         if(target.className === 'buy_btn'){
             const goodsId = target.dataset.id
             const cartList = list.find(function(item){return item.id === goodsId })
             const list1 = JSON.parse(window.localStorage.getItem('cart')) || []
            //  console.log(list1)
             if(!list1){
                 cartList.cart_number = 1
                 cartList.check = false
                 list1.push(cartList)
             }else{
                 let res1 = list1.some(function(item){return item.id === goodsId})
                 if(res1){
                     let index = list1.findIndex(function(item){return item.id === goodsId})
                     list1[index].cart_number++
                 }else{
                     cartList.check = false
                     cartList.cart_number = 1
                     list1.push(cartList)
                 }
             }
             window.localStorage.setItem('cart',JSON.stringify(list1))
             alert('加入购物车成功')
         }
     })
}

